<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ page import="com.xzl.xep.pojo.Payment"%>
<!-- 页首-->
<%@ include file="/WEB-INF/views/commons/header.jsp"%>

<!--main wrapper-->
<div class="wrapper row-offcanvas row-offcanvas-left">
    <!-- 左侧菜单 -->
    <%@ include file="/WEB-INF/views/commons/leftMenu.jsp"%>
        
         <!-- 正文 -->
            <aside class="right-side">
               <!-- 正文 头-->
                <section class="content-header">
                    <h1>
                        首页
                        <small></small>
                    </h1>
                    <ol class="breadcrumb">
                        <li><a href="#"><i class="fa fa-dashboard"></i> 首页</a></li>
                    </ol>
                </section>

                <!-- 内容-->
                <section class="content">
                    <div class="row">
                        <!-- 用户总数 -->
                        <div class="col-lg-3 col-xs-6 pointer" id="addCustomer"  rel="#overlay" >

                            <div class="small-box bg-aqua">
                                <div class="icon">
                                    <i class="ion ion-person-add"></i>
                                </div>
                                <div class="inner">
                                    <p>
                                        <strong id="todayCounts"> 新增用户：${today.counts} +</strong>
                                    </p>
                                    <p>
                                        <strong id="totalCounts"> 用户总数：${total.counts}</strong>
                                    </p>
                                </div>

                                <a class="small-box-footer">
                              新增会员
                            </a>
                            </div>
                        </div>
                        
                        <!-- 用户消费 -->
                        <div class="col-lg-3 col-xs-6 pointer" id="addOrder"  rel="#overlay" >

                            <div class="small-box bg-green">
                                <div class="icon">
                                    <i class="ion ion-ios7-cart-outline"></i>
                                </div>
                                <div class="inner">
                                    <p>
                                        <strong id="todaySpend"> 今日消费：${today.spend} +</strong>
                                        
                                    </p>
                                    <p>
                                        <strong id="totalSpend"> 累计消费：${total.spend}</strong>
                                    </p>
                                </div>

                                <a class="small-box-footer">
                              新增消费
                            </a>
                            </div>
                        </div>
                        
                        <!-- 用户充值 -->
                        <div class="col-lg-3 col-xs-6 pointer " id="addCredit"  rel="#overlay" >

                            <div class="small-box bg-teal">
                                <div class="icon">
                                    <i class="ion ion-social-usd-outline"></i>
                                </div>
                                <div class="inner">
                                    <p>
                                        <strong id="todayCredit"> 今日充值：${today.credit} +</strong>
                                    </p>
                                    <p>
                                        <strong id="totalCredit"> 累计充值：${total.credit}</strong>
                                    </p>
                                </div>

                                <a class="small-box-footer">
                              充值
                            </a>
                            </div>
                        </div>
                        
                    </div>
                    
                    <div class="box box-solid box-info">
                        <div class="box-header">
                            <h3 class="box-title">今日消费明细</h3>
                            <div class="box-tools pull-right">
                                <button class="btn btn-info btn-sm" data-widget="collapse"><i class="fa fa-minus"></i></button>
                                
                            </div>
                        </div>
                        <div class="box-body">
                            <table id="orderList" class="table table-bordered table-striped">
                               <thead>
                                                <tr>
                                                    <th></th>
                                                    <th>消费类型</th>
                                                    <th>支付类型</th>
                                                    <th>金额</th>
                                                    <th>时间</th>
                                                </tr>
                               </thead>
                               <tbody>
                                <c:forEach var="sale" items="${sales}"> 
                                    <tr >
                                        <td><span class="op fa fa-plus-square-o"  onclick="openOrder(this,${sale.id})"></span></td>
                                        <td>${sale.isCustomer == 1 ? "会员消费": "非会员消费"}</td>
                                        <td>
                                            
                                            <c:choose>  
  
                                                <c:when test="${sale.payment.way eq 'CASH'}"> 现金</c:when>  
                                                <c:when test="${sale.payment.way eq 'ALIPAY'}"> 支付宝</c:when>  
                                                <c:when test="${sale.payment.way eq 'BANK'}"> 银联</c:when>  
                                                <c:when test="${sale.payment.way eq 'BANLANCE'}"> 会员预存</c:when>  

                                               <c:otherwise>  未知  </c:otherwise>  
                                            </c:choose>  
                                        </td>
                                        <td>${sale.saleMoney} 元</td>
                                        <td><fmt:formatDate value="${sale.createTime}" pattern="HH:mm:ss"/></td>
                                    </tr >

                               </c:forEach>
                                    
                                </tbody>
                            </table>
                        </div>
                    </div>

                </section><!-- 内容结束 -->
            </aside><!-- 内容结束 -->
</div>
        
<!-- 页尾-->
<%@ include file="/WEB-INF/views/commons/end.jsp"%>

 <script>
    $(function() {
      var orders = $('#orderList').dataTable({"oLanguage": {"sUrl": "${res}/lib/datatables/jquery.dataTables.cn.txt"}});
    
      function getOpenHtml(tr,orderId){
          $.ajax({
            url:'${ctx}/order/details/'+orderId,
            dataType:'html',
            context:tr,
            success:function(html){
                $('.op',this).removeClass('fa-plus-square-o').addClass('fa-minus-square-o');
                orders.fnOpen( this, html, "" );
                
            }
          });
      }
      
      window.openOrder = function(el,id){
          var tr = $(el).parents('tr')[0];
          if ( orders.fnIsOpen(tr) ) {
               $(el).removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
               orders.fnClose( tr );
             } else {
               
               getOpenHtml(tr,id);
             }
      }
        
     
        
     
        
      $('#addCustomer').overlyDailog({
         title:'新增会员',
         url:'${ctx}/customer/new',
         size:4,
         berforeClose:function(is_ok,f){
            if(is_ok){
                $.ajax({
                    url:'${ctx}/customer/new',
                    data:f,
                    success:function(ret){      
                        $('#totalCounts').text('用户总数: '+ret.totalCounts);
                        $('#todayCounts').text('今日新增：'+ret.todayCounts+' +');
                        $('#todayCredit').text('今日充值： '+ ret.todayCredit+' +');
                        $('#totalCredit').text('累计充值： '+ ret.totalCredit+' 元');
                    }
                  });
            }
         }
        });  
       
        $('#addCredit').overlyDailog({
         title:'会员充值',
         url:'${ctx}/credit/add',
         size:4,
         onload: function(){
              
            $('#credit-mobile').autocomplete({
              source: '${ctx}/customer/queryMobile',
              minLength: 3,
              label : 'mobile',
              value : 'mobile',
              appendTo: ".form-group"  ,
              select: function( event, ui ) {
                if(ui.item){
                    $('#credit-customerId').val(ui.item.id);
                    $('#credit-name').val(ui.item.name);
                    $('#credit-cardno').val(ui.item.cardno);
                    $('#credit-balance').val(ui.item.balance);
                }
              }
            });
             
            $('#credit-cardno').autocomplete({
              source: '${ctx}/customer/queryCardno',
              minLength: 3,
              label : 'cardno',
              value : 'cardno',
              appendTo: ".form-group"  ,
              select: function( event, ui ) {
                if(ui.item){
                    $('#credit-customerId').val(ui.item.id);
                    $('#credit-name').val(ui.item.name);
                    $('#credit-balance').val(ui.item.balance);
                    $('#credit-mobile').val(ui.item.mobile);
                }
              }
            });
         },
         berforeClose:function(is_ok,f){
            if(is_ok && f.customerId && f.money){
                
                $.ajax({
                    url:'${ctx}/customer/credit',
                    data:f,
                    success:function(ret){      
                        $('#todayCredit').text('今日充值： '+ ret.todayCredit+' +');
                        $('#totalCredit').text('累计充值： '+ ret.totalCredit+' 元');
                    }
                  });
            }
             
            $('#credit-mobile').autocomplete('destroy');
            $('#credit-cardno').autocomplete('destroy');
         }
        }); 
      
        
     $('#addOrder').overlyDailog({
         title:'新增消费',
         url:'${ctx}/order/add',
         size:10,
         onload: function(){
             //是否会员消费
            $('#order-is-customer').on('switchChange.bootstrapSwitch', function(event, state) {
                    if(state){
                        $('#balance-way').removeAttr("disabled").attr('checked','checked'); 
                        $('.order-customer').removeClass('hide');
                    }else{
                        $('#balance-way').attr("disabled","disabled").removeAttr('checked'); 
                        $('#cash-way').attr('checked','checked'); 
                        $('.order-customer').addClass('hide');
                    }
                 
                });
             
              //是否充值
            $('#order-is-credit').on('switchChange.bootstrapSwitch', function(event, state) {
                    if(state){
                        $('.order-credit').removeClass('hide');
                        $('#cash-way').attr('checked','checked'); 
                        $('#balance-way').attr("disabled","disabled"); 
                    }else{
                        $('.order-credit').addClass('hide');
                        $('#balance-way').removeAttr("disabled").attr('checked','checked');  
                    }
                 
                });
             
             $('#order-mobile').autocomplete({
              source: '${ctx}/customer/queryMobile',
              minLength: 3,
              label : 'mobile',
              value : 'mobile',
              appendTo: ".form-group"  ,
              select: function( event, ui ) {
                if(ui.item){
                    $('#order-customerId').val(ui.item.id);
                    $('#order-name').val(ui.item.name);
                    $('#order-cardno').val(ui.item.cardno);
                    $('#order-balance').val(ui.item.balance);
                }
              }
            });
             
            $('#order-cardno').autocomplete({
              source: '${ctx}/customer/queryCardno',
              minLength: 3,
              label : 'cardno',
              value : 'cardno',
              appendTo: ".form-group"  ,
              select: function( event, ui ) {
                if(ui.item){
                    $('#order-customerId').val(ui.item.id);
                    $('#order-name').val(ui.item.name);
                    $('#order-balance').val(ui.item.balance);
                    $('#order-mobile').val(ui.item.mobile);
                }
              }
            });
             
             
            $('.order-jm').autocomplete({
              source: '${ctx}/product/queryCode',
              minLength: 2,
              label : 'code',
              value : 'code',
              appendTo: ".form-group"  ,
              select: addPorduct
            });
         },
         berforeClose:function(is_ok,f){
            if(is_ok){
                console.log(f);
                
                if(f.isCustomer == 1 &&  f.way == 3 &&  f.totalMoney > f.balance ){
                    alert('余额不足！');
                    return false;
                }
                
                if(f.isCredit == 1 && f.totalMoney > (Number(f.balance).add(f.credit))){
                    alert('充值金额不足！');
                    return false;
                }
                    
            
                var param = {isCustomer:f.isCustomer,customerId:f.customerId, isCredit:f.isCredit, credit: f.credit, totalMoney:f.totalMoney, way: f.way };
                
                if(f.code instanceof Array){
                   param.code = f.code.join(',');
                }else{
                   param.code = f.code;
                }
                  
                if(f.counts instanceof Array){
                   param.counts = f.counts.join(',');
                }else{
                   param.counts = f.counts;
                }
                
                $.ajax({
                    url:'${ctx}/order/add',
                    data:param,
                    success:function(ret){      
                        var sale = ret.sale;
                        var time =  new Date(sale.createTime);
                        orders.fnAddData([
                                    '<span class="op fa fa-plus-square-o"  onclick="openOrder(this,'+sale.id+')"></span>',
                                    ['非会员消费','会员消费'][sale.isCustomer],
                                    {'<%=Payment.CASH_WAY%>':'现金','<%=Payment.ALIPAY_WAY%>':'支付宝','<%=Payment.BANK_WAY%>':'银联','<%=Payment.BALANCE_WAY%>':'会员预存'}[sale.payment.way],
                                    sale.saleMoney +' 元' ,
                                    time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()
                                ]);
                        orders.fnDraw();
                        
                        
                        
                        $('#todayCredit').text('今日充值： '+ ret.todayCredit+' +');
                        $('#totalCredit').text('累计充值： '+ ret.totalCredit+' 元');
                        $('#todaySpend').text('今日消费： '+ ret.todaySpend+' +');
                        $('#totalSpend').text('累计消费： '+ ret.totalSpend+' 元');
                    }
                });
            }
             
             
            //destory
            $('.order-jm').autocomplete('destroy');
            $('#order-mobile').autocomplete('destroy');
            $('#order-cardno').autocomplete('destroy');
            $('#order-is-credit').bootstrapSwitch('destroy');
            $('#order-is-customer').bootstrapSwitch('destroy');
         }
        }); 
        
        
        function addPorduct(event, ui){
            if(ui.item){
                   var tr = $(this).parents("tr"), row = tr.attr('data-row') +1;
                  var totalMoney = Number($('#order-money').val());
                 $('#order-money').val(totalMoney.add(ui.item.price).sub($('.order-product-money',tr).text()));
              
                   $('.order-product-name',tr).text(ui.item.name);
                   $('.order-product-price',tr).text(ui.item.price);
                   $('.order-product-counts',tr).val(1);
                   $('.order-product-money',tr).text(ui.item.price);
                   
                
                  
                   
                   var next_html = '<tr data-row="'+row+'">'
                                  +'<td class="col-md-2"><div class="form-group"><input type="text" name="code" class="form-control order-jm input-sm"></div></td>'
                                  +'<td class="order-product-name"></td>'
                                  +'<td class="order-product-price"></td>'
                                  +'<td class="col-md-1"><div class="form-group"><input type="text" name="counts" class="form-control input-sm order-product-counts" onchange="changeCount(this)"></div></td>'
                                  +'<td class="order-product-money"></td> '
                                  +'<td ><a  onclick="delProduct(this)"><i class="fa fa-times"/></a> </td>'
                                  +'</tr>';
                   tr.after(next_html); 
                
                   $('.order-jm',tr.next()).autocomplete({
                      source: '${ctx}/product/queryCode',
                      minLength: 2,
                      label : 'code',
                      value : 'code',
                      appendTo: ".form-group"  ,
                      select: addPorduct
                    });
            }
        
        }
        
        window.delProduct = function(el){
             var tr = $(el).parents("tr");
            if(tr.attr('data-row') == 1) return ;
            $('.order-jm',tr).autocomplete('destroy');
            
            var totalMoney = Number($('#order-money').val());
                
            $('#order-money').val(totalMoney.sub($('.order-product-money',tr).text()));
            
            tr.remove();
        };
        
        window.changeCount = function(el){
            var tr = $(el).parents("tr"), count = $(el).val();
            
            
            var totalMoney = Number($('#order-money').val()), price = Number($('.order-product-price',tr).text());
            
            var money = price.mul(count);
            
            
            $('#order-money').val(totalMoney.add(money).sub($('.order-product-money',tr).text()) );
            
            
            $('.order-product-money',tr).text(money);

        };
        
        window.addNullOrder = function(el){
             var row = new Date().getTime();
             var next_html = '<tr data-row="'+row+'">'
                                  +'<td class="col-md-2"><div class="form-group"><input type="text" name="code" class="form-control order-jm input-sm"></div></td>'
                                  +'<td class="order-product-name"></td>'
                                  +'<td class="order-product-price"></td>'
                                  +'<td class="col-md-1"><div class="form-group"><input type="text" name="counts" class="form-control input-sm order-product-counts" onchange="changeCount(this)"></div></td>'
                                  +'<td class="order-product-money"></td> '
                                  +'<td ><a  onclick="delProduct(this)"><i class="fa fa-times"/></a> </td>'
                                  +'</tr>';
            
            $('#order-table').append(next_html);
            
            $('[data-row='+row+'] .order-jm').autocomplete({
                      source: '${ctx}/product/queryCode',
                      minLength: 2,
                      label : 'code',
                      value : 'code',
                      appendTo: ".form-group"  ,
                      select: addPorduct
                    });
        }
    });

</script>
